package com.zk.erp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zk.erp.entity.Functions;
import com.zk.erp.entity.Role;
import com.zk.erp.entity.User;
import com.zk.erp.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getUsername, s));
        if (user==null){
            throw new UsernameNotFoundException("用户名没找到");
        }
        List<Role> roles = userMapper.selectRolesByUsername(user.getUsername());
        List<Functions> functions = userMapper.selectFunctionsByUsername(user.getUsername());
        StringBuilder stringBuilder = new StringBuilder();
        roles.forEach(role -> stringBuilder.append(role.getName()+","));
        functions.forEach(functions1 -> stringBuilder.append(functions1.getName()+","));
        if (stringBuilder.length()>0){
            stringBuilder.deleteCharAt(stringBuilder.length()-1);
        }
        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),
                AuthorityUtils.commaSeparatedStringToAuthorityList(stringBuilder.toString()));

    }
}
